﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XNA_TD
{
    public class Kamera : IRunable, IUpdate
    {
        public Vector3 position;
        Vector3 lookAt;
        float scale = .5f;
        float oldScrollWheel = 0;
        public Kamera()
            : base(Priority.Kamera)
        {
            lookAt = new Vector3(terrain.terrainWidth / 2, 0, terrain.terrainHeight / 2);
            //CalculateViewMatrix();
            CalculateProjectionMatrix();
            kamera = this;
            UpdateShader();
        }

        public void Update()
        {
            float speed = (float)(gameTime.ElapsedGameTime.TotalSeconds * 30);

            int forward = 0;
            int right = 0;

            var state = Keyboard.GetState();

            //position += Vector3.Transform((float)gameTime.ElapsedGameTime.TotalSeconds * new Vector3(forward, 0, right), Matrix.CreateRotationY(yaw));
            if (state.IsKeyDown(Keys.S) || state.IsKeyDown(Keys.Down))
                forward += 1;
            if (state.IsKeyDown(Keys.W) || state.IsKeyDown(Keys.Up))
                forward -= 1;
            if (state.IsKeyDown(Keys.A) || state.IsKeyDown(Keys.Left))
                right -= 1;
            if (state.IsKeyDown(Keys.D) || state.IsKeyDown(Keys.Right))
                right += 1;

            lookAt.Z += forward * speed;
            lookAt.X += right * speed;

            lookAt.X = Math.Max(35, Math.Min(lookAt.X, 65));
            lookAt.Z = Math.Max(20, Math.Min(lookAt.Z, 40));
            scale = Math.Min(.5f, Math.Max(.3f, scale + (oldScrollWheel - (float)Mouse.GetState().ScrollWheelValue) / 5000f));
            oldScrollWheel = Mouse.GetState().ScrollWheelValue;
            CalculateViewMatrix();
            UpdateShader();
        }

        public void CalculateViewMatrix()
        {
            position = lookAt + new Vector3(0, 20, 20) * scale;
            viewMatrix = Matrix.CreateLookAt(position, lookAt, Vector3.Up);
        }

        public void CalculateProjectionMatrix()
        {
            float aspect = graphics.GraphicsDevice.DisplayMode.AspectRatio;
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(60),
                aspect,
                1f,
                100f);
        }

        public void UpdateShader()
        {
            shader.Parameters["ViewProjection"].SetValue(viewMatrix * projectionMatrix);
        }

        public override void Load()
        {
        }

        public override void UnLoad()
        {
        }
    }
}
